﻿using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhaoXi.MSACommerce.UserCases.Common.Exception;

namespace Zhaoxi.MSACommerce.HttpApi.Common.Infrastructure
{
    public class UserCaseExceptionHandler : IExceptionHandler
    {
        private readonly Dictionary<Type, Func<HttpContext, Exception, Task>> _exceptionHandlers = new()
        {
            {typeof(ValidationException), HandleValidationException},
            {typeof(ForbiddenException), HandlerForbiddenExceptionAsync}
        };

        public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
        {
            var exceptionType = exception.GetType();
            if (!_exceptionHandlers.TryGetValue(exceptionType, out var handler)) { return false; }

            await handler.Invoke(httpContext, exception);
            return true;

        }
        private static async Task HandlerForbiddenExceptionAsync(HttpContext content, Exception exception)
        {
            content.Response.StatusCode = StatusCodes.Status403Forbidden;
            await content.Response.WriteAsJsonAsync(new ProblemDetails
            {
                Status = StatusCodes.Status403Forbidden,
                Title = "Forbidden",
                Type = "https://developer.mozilla.org/zh-Cn/docs/web/HTTP/Status/403"
            });
        }

        private static async Task HandleValidationException(HttpContext content, Exception exception)
        {
            var validationException = (ValidationException)exception;
            content.Response.StatusCode = StatusCodes.Status400BadRequest;

            await content.Response.WriteAsJsonAsync(new ValidationProblemDetails(validationException.Errors)
            {
                Status = StatusCodes.Status400BadRequest,
                Type = "https://developer.mozilla.org/zh-Cn/docs/web/HTTP/Status/400"
            });
        }
    }
}
